<script setup>
  import emptyIcon from '@/assets/image/com_empty.png'
  import {productList, queryGroupInfo, categoryInfo} from '@/api/product'
  import useSettingStore from '@/store/modules/setting'
  import {t} from '@/locales'

  const currency = ref(useSettingStore().global.currencySymbol || '')
  const route = useRoute()
  const router = useRouter()

  const emits = defineEmits(['reset'])
  const props = defineProps({
    isSearch: {
      type: Boolean,
      default: false
    }
  })
  // 搜索过
  const searched = ref(false)
  const defaultParams = {
    pageSize: 20,
    pageNum: 1,
    categoryId: '',
    productName: '',
    groupId: '',
    sort: 0
  }
  const queryParams = reactive({...defaultParams})
  const showPicker = ref(false)
  const keyword = ref('')
  const category = ref({})
  const groupInfo = ref({})
  const sortOpt = ref([
    {text: t('commodity.recommend'), value: 0},
    {text: t('commodity.new'), value: 1},
    {text: t('commodity.saleAsc'), value: 2},
    {text: t('commodity.saleDes'), value: 3},
    {text: t('commodity.priceAsc'), value: 4},
    {text: t('commodity.priceDes'), value: 5}
  ])
  const selectedSort = ref(sortOpt.value[0])
  const productOb = ref({
    total: 0,
    rows: []
  })
  const loading = ref(false)
  const finished = ref(true)
  const title = computed(() => {
    if(searched.value && props.isSearch) return keyword.value
    return category.value.name || groupInfo.value.name || ''
  })
  const subTitle = computed(() => {
    if(searched.value && props.isSearch) return `${t('commodity.total')}${productOb.value.total}${t('commodity.results')}`
    return groupInfo.value.remark || ''
  })

  watch(() => route.query, val => {
    if(val.categoryId) {
      category.value = {}
      selectedSort.value = sortOpt.value[0]
      Object.assign(queryParams, defaultParams)
      productOb.value = {total: 0, rows: []}
      init()
    }
  }, {deep: true})

  function resetParams() {
    Object.assign(queryParams, defaultParams)
  }
  // 搜索商品
  function clickSearch() {
    if(!keyword.value) return
    resetParams()
    searched.value = true
    queryProduct(true)
  }
  // 选择排序
  function onSelectSort({selectedOptions}) {
    showPicker.value = false
    queryParams.pageNum = 1
    selectedSort.value = selectedOptions[0]
    queryProduct(true)
  }
  // 获取商品列表
  function queryProduct(flag) {
    const {query} = router.currentRoute?.value
    const {categoryId='', groupId} = query || {}
    Object.assign(queryParams, {
      productName: keyword.value,
      categoryId,
      groupId,
      sort: selectedSort.value.value || 0
    })
    loading.value = true
    finished.value = false
    productList(queryParams).then(res => {
      let {rows: pageRows, total} = res
      pageRows.forEach(it => {
        it.image = it.image.split(',')[0]
      })
      const rows = [...productOb.value.rows, ...pageRows]
      loading.value = false
      if(rows.length < total) {
        queryParams.pageNum++
      } else {
        finished.value = true
      }
      productOb.value = {total,  rows: flag?pageRows:rows}
    })
  }
  // 分页
  function onLoad() {
    queryProduct()
  }
  // 初始化数据
  function init() {
    const {categoryId,  groupId} = route.query
    if(!props.isSearch) {
      queryProduct()
    }
    // 分类详情
    if(categoryId) {
      categoryInfo(categoryId).then(r => {
        category.value = r.data
      })
    }
    if(groupId) {
      queryGroupInfo(groupId).then(r => {
        groupInfo.value = r.data
      })
    }
  }
  // 跳转商详
  function toDetail(it) {
    if(props.isSearch) emits('reset')
    router.push(`/product-detail/${it.productId}`)
  }

  init()
</script>

<template>
  <div class="commodity-list">
    <div class="search-cell">
      <van-field
        v-if="isSearch"
        class="search-input"
        left-icon="search"
        v-model.trim="keyword"
        :placeholder="`${$t('common.search')}...`"
      >
        <template #button>
          <span @click="clickSearch">{{$t('common.search')}}</span>
        </template>
      </van-field>
      <div class="s-con" v-if="searched || !props.isSearch">
        <p class="title">{{title}}</p>
        <p class="sub-title">{{subTitle}}</p>
      </div>
      <van-field
        v-if="!isSearch || productOb.total"
        class="select"
        right-icon="arrow-down"
        readonly
        v-model="selectedSort.text"
        @click="showPicker = true"
      />
    </div>
    <!-- 商品列表 -->
    <div class="pro-cell" v-if="productOb.rows.length">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :finished-text="$t('commodity.noMore')"
        :loading-text="$t('commodity.loading')"
        @load="onLoad"
      >
        <van-row :gutter="[9, 16]" class="pro-row">
          <van-col
            span="12"
            v-for="it in productOb.rows"
            :key="it.productId"
            @click="toDetail(it)"
          >
            <img :src="it.image" class="img"/>
            <div class="pro-info">
              <p class="text-overflow">{{it.productName}}</p>
              <p class="intro text-overflow">{{it.introduce}}</p>
              <p><span>{{currency}}</span>{{it.minPrice}}</p>
            </div>
          </van-col>
        </van-row>
      </van-list>
    </div>
    <div class="empty" v-if="!productOb.rows.length&&!loading&&!isSearch">
      <img :src="emptyIcon"/>
      <p>{{$t('commodity.noCom')}}</p>
    </div>
    <!-- 排序选择 -->
    <van-popup v-model:show="showPicker" round position="bottom" style="height: 45%;">
      <van-picker
        :columns="sortOpt"
        @cancel="showPicker = false"
        @confirm="onSelectSort"
      />
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
  .commodity-list {
    height: 100%;
    // overflow: auto;
    padding: 0 16px 30px;
    .search-cell {
      :deep(.search-input){
        height: 36px;
        border: 1px solid #262626;
        border-radius: 2px;
        padding: 0 12px;
        .van-field__left-icon {
          line-height: 36px;
        }
        .van-field__button  {
          span {
            font-size: 14px;
            padding-left: 12px;
            display: inline-block;
            border-left: 1px #E5E5E5 solid;
            color: #262626;
          }
        }
        .van-field__body {
          height: 36px;
        }
      }
      :deep(.select) {
        height: 44px;
        border: 1px solid #E5E5E5;
        border-radius: 2px;
        padding: 0 12px;
        margin: 24px 0 16px;
        .van-field__body {
          height: 44px;
        }
      }
      .s-con {
        padding-top: 24px;
        p {
          text-align: center;
          &.title {
            font-size: 20px;
          }
          &.sub-title {
            margin-top: 5px;
            font-size: 14px;
            color: #8C8C8C;
          }
        }
      }
    }

    .pro-cell  {
      .pro-row  {
        .van-col {
          .img {
            height: 190px;
            width: 100%;
            margin-bottom: 8px;
          }
          .pro-info {
            padding: 0 12px;
            p {
              font-weight: 600;
              font-size: 14px;
              text-align: center;
              margin-bottom: 0;
              &:nth-of-type(1) {
                margin-bottom: 4px;
              }
              &.intro {
                color: #939599;
                margin-bottom: 4px;
                font-weight: 400;
                font-size: 12px;
              }
            }
          }
        }
      }
    }
    .empty {
      text-align: center;
      margin-top: 50px;
      img {
        height: 100px;
        width: 100px;
      }
      p {
        font-size: 14px;
        color: #8C8C8C;
      }
    }
  }
</style>